<?php

namespace app\controllers;

use yii\rest\ActiveController;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use yii\filters\auth\QueryParamAuth;
use app\models\LoginForm;
use app\models\AdminUser;
use yii;

class AdminuserController extends ActiveController
{
    public $modelClass = 'app\models\adminuser';//对应的数据模型处理控制器  

    public function behaviors() 
    {
        return ArrayHelper::merge (parent::behaviors(), [ 
                'authenticator' => [ 
                    'class' => QueryParamAuth::className(),
                    'tokenParam' => 'token',
                    'optional' => [
                        'login',
                        'signup-test'
                    ],
                ] 
        ] );
    }

    /**
    * 登录
    */
    public function actionLogin()
    {
        $model = new LoginForm;
        //echo '<pre>'; print_r(\Yii::$app->security->generatePasswordHash('123123'));exit;
        $model->setAttributes(Yii::$app->request->post());
        if ($user = $model->login()) {
            if ($user) {
                return ['accesstoken'=>$user->accesstoken];
            } else {
                return $user->errors;
            }
        } else {
            return $model->errors;
        }
    }

    /**
    * 获取用户信息
    */
    public function actionUserProfile ($token)
    {
        // 到这一步，token都认为是有效的了
        // 下面只需要实现业务逻辑即可，下面仅仅作为案例，比如你可能需要关联其他表获取用户信息等等
        $user = AdminUser::findIdentityByAccessToken($token);
        return [
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
        ];
    }

}
